﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ninject;
using Agr.CQRS.Domain.Commands;

namespace Agr.CQRS.Infrastructure.Commands
{
    public class CommandHandlerFactory
    {
        private IKernel dicontainer;
        public CommandHandlerFactory(IKernel dicontainer)
        {
            this.dicontainer = dicontainer;
        }

        public CommandHandler CreateCommandHandlerFor(Command cmd)
        {
            string handlerName = string.Concat(cmd.GetType().FullName, "Handler");
            handlerName = cmd.GetType().AssemblyQualifiedName.Replace(cmd.GetType().FullName, handlerName); //add assembly info
            var handlerType = Type.GetType(handlerName);

            CommandHandler handler = null;

            if (handlerType != null) 
                handler = dicontainer.Get(handlerType) as CommandHandler;

            if (handler == null)
                throw new InvalidCommandException("handlertype {0} not found", handlerName);

            return handler;
        }

    }
}
